package com.bitcs.accesscontrol.service;

import com.bitcs.accesscontrol.dao.entity.AccessControlPO;
import com.bitcs.accesscontrol.dao.entity.AccessLogPO;
import com.bitcs.accesscontrol.dao.entity.RequestVO;
import com.bitcs.accesscontrol.dao.mapper.AccessControllMapper;
import com.bitcs.accesscontrol.util.CodeMessage;
import com.bitcs.accesscontrol.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author GeChen
 * @Description
 * @date 2019/10/30 17:02
 */
@Service
public class AccessService {
    @Autowired
    private AccessControllMapper accessControllMapper;

    /**
     * 获取所有的权限信息
     *
     * @return
     */
    public String getAllPOs() {
        List<AccessControlPO> accessControlPOS = accessControllMapper.getAllPOs();
        return ResponseUtil.getResponseString(CodeMessage.SUCCESSFUL, CodeMessage.INFO_SUCCESSFUL, accessControlPOS);
    }

    /**
     * 根据RequestVO查询对应的权限信息
     *
     * @param requestVO
     * @return
     */
    public String getAccessByVO(RequestVO requestVO) {
        String appId = requestVO.getAppId();
        String type = requestVO.getType();
        List<AccessControlPO> accessControlPOS = accessControllMapper.getPOByAppid(appId);
        if (accessControlPOS.size() == 0) {
            return ResponseUtil.getResponseString(CodeMessage.ID_NOT_EXIST, CodeMessage.INFO_ID_NOT_EXIST, false);
        }
        AccessControlPO accessControlPO = accessControllMapper.getPOByAppidAndType(appId, type);
        boolean available = false;
        boolean chargeByTime = false;
        /**
         * 按年份收费
         */
        if (accessControlPO.getRemainCount() == AccessControlPO.Const.CHARGED_BY_TIME_COUNT) {
            available = new Date().before(accessControlPO.getExpiredTime());
            chargeByTime = true;
        }
        /**
         * 按次数收费
         */
        else {
            available = accessControlPO.getRemainCount() > 0;
        }
        if (!available) {
            return ResponseUtil.getResponseString(CodeMessage.SERVICE_NOT_AVAILABLE, CodeMessage.INFO_SERVICE_NOT_AVAILABLE, false);
        }
        //按次数收费再减少次数
        if (!chargeByTime) {
            accessControllMapper.updateRemainCount(accessControlPO.getId());
        }
        return ResponseUtil.getResponseString(CodeMessage.SUCCESSFUL, CodeMessage.INFO_SUCCESSFUL, true);
    }

    /**
     * 将日志信息插入到日志表
     *
     * @param accessLogPO
     * @return
     */
    public int insertAccessLog(AccessLogPO accessLogPO) {
        return accessControllMapper.insertAccessLog(accessLogPO.getOperationName(),
                accessLogPO.getMethodName(), accessLogPO.getExceptionDetail(), accessLogPO.getParams(), accessLogPO.getTransferTime(),
                accessLogPO.getRemoteAddr(), accessLogPO.getRemotePort());
    }
}
